var yourRoninUrl = 'http://binn.in.ua/invoices/jsonp.php';
var domain = ''; //ronin domain
var token = ''; //secret token
var dataLoaded = false; //data loaded from ronin (auth OK)
var totalTime = 0; //collect time form start to submit
var collecttime = 0; //collect time from start to pause
var startTime = 0; //system time on start event
var timerStatus = false; //timer state
var oSelectedTimeZone = System.Time.currentTimeZone; //system timezone

var lWidth = 250;
var lHeight = 350;
var sWidth = 250;
var sHeight = 100;

// Declare the dock and undock event handlers.
//System.Gadget.onDock = CheckDockState;
//System.Gadget.onUndock = CheckDockState;


function getDataFromRonin(){
	
	var oReq = new window.XMLHttpRequest;
	url = 'https://binnua.roninapp.com/clients?page=2';

	if (oReq != null) {
		oReq.open("GET", url, true, token, token);
		oReq.setRequestHeader('Accept', 'application/json');
		oReq.setRequestHeader('Content-type', 'application/json');
		
		oReq.onreadystatechange = function(){
			if (oReq.readyState == 4 /* complete */) {
				if (oReq.status == 200) {
					document.body.innerHTML = oReq.responseText;
				}
			}
		};
		oReq.send();
		
	}
	
	//load client list
	$.getJSON(yourRoninUrl + "?jsoncallback=?",
	  {
		domain: domain,
		token: token,
		type: "clients", 
		page: 1 //TODO download all clients
	  },
	  function(data) {
	  //
		if(data && data != ''){
			dataLoaded = true;
			$('#no-auth-cont').addClass('hide');
			$('#form-cont').removeClass('hide');
			$('body').addClass('undocked');
			$(document.body).addClass('undocked')
                    .css('width', lWidth+'px')
                    .css('height', lHeight+'px')
		}
		dataStored = data;
			if(data.clients) dataStored = data.clients;
		  optionString = '<option value="">Select from list</option>';
		  for(i = 0; i < dataStored.length; i++){
			optionString += '<option value="' + dataStored[i].id + '">' + dataStored[i].name + '</option>';
		  }
		  $('#client-list').html(optionString);
	  });
	
	//load clients project
	$('#client-list').get(0).onchange = function(){
		var clientId = $(this).val();
		if(clientId != ''){
		
		$.getJSON(yourRoninUrl + "?jsoncallback=?",
		  {
			domain: domain,
			token: token,
			type: "projects", 
			client: clientId, 
			page: 1
		  },
		  function(data) {
			  var optionString = '<option value="">Select from list</option>';
			  for(i = 0; i < data.projects.length; i++){
				optionString += '<option value="' + data.projects[i].id + '">' + data.projects[i].name + '</option>';
			  }
			  if(data.page_count > 1){
			  
					for(i = 2; i <= data.page_count; i++){
						$.getJSON(yourRoninUrl + "?jsoncallback=?",
						  {
							domain: domain,
							token: token,
							type: "projects", 
							client: clientId, 
							page: i
						  },
						  function(data) {
							for(j = 0; j < data.projects.length; j++){
								optionString += '<option value="' + data.projects[j].id + '">' + data.projects[j].name + '</option>';
							}
							$('#project-list').html(optionString);
						  });
					}
			  } else {
				$('#project-list').html(optionString);
			  }
		  });
	  }
	  }
	  
	//show old hours list
	$('#project-list').get(0).onchange = function(){
		if($(this).val() != ''){
			$.getJSON(yourRoninUrl + "?jsoncallback=?",
			  {
				domain: domain,
				token: token,
				type: "hours", 
				projectId: $(this).val()
			  },
			  function(data) {
				  optionString = '<option value="">Select from list</option>';
				  for(i = 0; i < data.hours.length; i++){
					optionString += '<option value="' + data.hours[i].title + '">' + data.hours[i].title + '</option>';
				  }
				  $('#hours-list').html(optionString);
			  });
		} else {
			$('#hours-list').html('<option>Select the project first</option>');
		}
	};
	$('#hours-list').get(0).onchange = function(){
		if($(this).val() != ''){
			$('#new-hours').val('');
		}
	};
	$('#new-hours').get(0).onkeyup = function(){
		if($(this).val() != ''){
			$('#hours-list').val('');
		}
	};
	
	function checkTimer(){
		if(timerStatus){
						
			curTimeInfo = System.Time.getLocalTime(oSelectedTimeZone);
			curTime = Date.parse(curTimeInfo);
			
			collecttime = (curTime - startTime) / 1000;
			rTime = collecttime + totalTime;
			hoursv = Math.floor(rTime / 3600);
			mins = Math.floor((rTime - hoursv*3600 ) / 60);
			sec = rTime - hoursv*3600 - mins*60;
				if(hoursv < 10) hoursv = '0' + hoursv;
				if(mins < 10) mins = '0' + mins;
				if(sec < 10) sec = '0' + sec;
			$("#hours").html(hoursv);
			$("#minutes").html(mins);
			$("#seconds").html(sec);
		}
	}
	setInterval(checkTimer, 1000);
	
	//Start/Stop timer function
	$('#startButton').get(0).onclick = function(){
		timerStatus = true;
		sTimeInfo = System.Time.getLocalTime(oSelectedTimeZone);
		startTime = Date.parse(sTimeInfo);
		
		$('#startButton').addClass('hide');
		$('#pauseButton').removeClass('hide');
		$('#submitButton').addClass('hide');
		$('#clearButton').addClass('hide');
		
		$('#hideFields').trigger('click');
	}
	$('#pauseButton').get(0).onclick = function(){
		timerStatus = false;
		
		totalTime += collecttime;
		hoursToSubmit = Math.round(totalTime / 3.6) / 1000;
		$('#new-time').val(hoursToSubmit);
		
		$('#startButton').removeClass('hide');
		$('#pauseButton').addClass('hide');
		$('#submitButton').removeClass('hide');
		$('#clearButton').removeClass('hide');
		
		$('#showFields').trigger('click');
	}
	$('#clearButton').get(0).onclick = function(){
		timerStatus = false;
		
		totalTime = 0;
		$("#hours").html('00');
		$("#minutes").html('00');
		$("#seconds").html('00');
		$('#new-time').val('');
		
		$('#startButton').removeClass('hide');
		$('#pauseButton').addClass('hide');
		$('#submitButton').addClass('hide');
		$('#clearButton').addClass('hide');
		
		
	}
	
	//Submit data
	$('#submitButton').get(0).onclick = function(){
		projectId = $('#project-list').find('option:selected').val();
		taskHours = 0;
			if($('#new-time').val() != '' && !isNaN($('#new-time').val())){
				taskHours = $('#new-time').val();
			}
		taskTitle = '';
			if($('#hours-list').val() != ''){
				taskTitle = $('#hours-list').val();
			} else {
				taskTitle = $('#new-hours').val();
			}
		
		if(taskTitle != '' && taskHours != 0){
		
			$.getJSON(yourRoninUrl + "?jsoncallback=?",
			  {
				domain: domain,
				token: token,
				projectId: projectId, 
				hours: taskHours, 
				title: taskTitle
			  },
			  function(data) {
			  if(data && data != ''){
					
					totalTime = 0;
					$("#hours").html('00');
					$("#minutes").html('00');
					$("#seconds").html('00');
					$('#new-time').val('');
					$('#submitButton').addClass('hide');
					
					$('.buttons').before('<span class="system-info">Time succesfully submitted</span>');
					
				} else {
					$('.buttons').before('<span class="system-info">Some error occured. Please, try again later</span>');
				}
				
				function clearMessage(){
					$('.system-info').hide(1000, function(){
						$('.system-info').remove();
					});
				}
				setTimeout(clearMessage, 2000);
				
				$('.system-info').get(0).onclick = function(){
					$(this).remove();
				};
				
			  });
		} else {
			$('.buttons').before('<span class="system-info">Select project and task before submit</span>');
			
			function clearMessage(){
				$('.system-info').hide(1000, function(){
					$('.system-info').remove();
				});
			}
			setTimeout(clearMessage, 2000);
			
			$('.system-info').get(0).onclick = function(){
				$(this).hide(500, function(){
					$(this).remove();
				});
			};
		}
		  
		return false;  
	}
}

function checkSettings(){
	domain = System.Gadget.Settings.readString('roninDomain');
	token = System.Gadget.Settings.readString('roninToken');
	
	if(domain == '' && token == ''){
		domain = 'binnua';
		token = 'n9zNkSRDaltdryMlP1p1yeg28';
		System.Gadget.Settings.writeString('roninDomain', domain);
		System.Gadget.Settings.writeString('roninToken', token);
	}
	
	if(domain != '' && token != '' && !dataLoaded && $('#domain-input').length == 0){
		getDataFromRonin();
	}
}
if(!dataLoaded){
	setInterval(checkSettings, 1000);
}
	
//load settings on settings page
function settingsClosing(event) {
  if (event.closeAction == event.Action.commit) {
	domain = $('#domain-input').val();
	token = $('#token-input').val();
  
    System.Gadget.Settings.writeString('roninDomain', domain);
	System.Gadget.Settings.writeString('roninToken', token);
  }
}

function init(){
	System.Gadget.settingsUI = 'settings.html';
	System.Gadget.onSettingsClosing = settingsClosing;
	System.Gadget.Settings.write("PrivateSetting_GadgetOpacity", 95);
	
	domain = System.Gadget.Settings.readString('roninDomain');
	token = System.Gadget.Settings.readString('roninToken');
	
	if($('#domain-input').length > 0){
		$('#domain-input').val(domain);
		$('#token-input').val(token);
	}

	checkSettings();
	//CheckDockState();

$('#hideFields').get(0).onclick = function(){
	$('#hideFields').addClass('hide');
	$('#showFields').removeClass('hide');
	
	$('.toHide').addClass('hide');
	$(document.body).addClass('docked')
					.css('width', sWidth+'px')
                    .css('height', sHeight+'px')
}
$('#showFields').get(0).onclick = function(){
	$('#hideFields').removeClass('hide');
	$('#showFields').addClass('hide');
	
	$('.toHide').removeClass('hide');
	$(document.body).removeClass('docked')
					.css('width', lWidth+'px')
                    .css('height', lHeight+'px')
}



}
function CheckDockState(){

	if (System.Gadget.docked)
    {
        $('#hideFields').trigger('click');
    }
    else
    {
        $('#showFields').trigger('click');
    }
}


